# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         utils.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2020/10/27 17:04
# -------------------------------------------------------------------------------
import json
import logging
import re
from datetime import datetime

from apps.HttpAutoTestService.models import TestcaseResult, TestsuiteResult
from apps.HttpAutoTestService.models import Parameter
from apps.CeleryScheduledTaskService.HttpAutoTestService.send_mail_task import send_mail
from utils.dingtalk_client import DingTalkClient

logger = logging.getLogger(__name__)

# 绝对http url正则表达式
absolute_http_url_regexp = re.compile(r"^https?://", re.I)


def send_testreport(report_type, version, executor, is_periodictask):
    """
    发送测试报告
    Args:
        report_type: 报告类型（testcase、testsuite）
        version: 版本号
        executor: 当前执行(登录)用户
        is_periodictask: 标记是否是定时任务

    Returns:

    """
    testreport_status = {
        'init': '初始状态',
        'pass': '全部通过',
        'fail': '全部失败',
        'partial_pass': '部分通过'
    }
    executor_real_name = '定时任务' if is_periodictask else executor.real_name
    execute_time = datetime.fromtimestamp(int(version) / 1000).strftime("%Y-%m-%d %H:%M:%S")
    mail_subject = dingtalk_title = '用例测试报告' if report_type == 'testcase' else '场景测试报告'
    if report_type == 'testcase':
        result = TestcaseResult.objects.filter(is_deleted=False, version=version).values('status').order_by().distinct()
    else:
        result = TestsuiteResult.objects.filter(is_deleted=False, version=version).values('status').order_by().distinct()
    if result:
        if len(result) == 1:
            result_status = result.first().get('status')
        else:
            result_status = 'PARTIAL_PASS'
    else:
        result_status = 'INITIAL'
    result_status = 'init' if result_status == 'INITIAL' else result_status.lower()

    report_parameter = Parameter.objects.filter(key='REPORT', is_deleted=False).first()
    if report_parameter:
        value = json.loads(report_parameter.value)
        if value:
            # 访问地址
            url = value.get('URL')
            if url:
                url = url.strip('/')
                if not absolute_http_url_regexp.match(url.lower()):
                    url = f'https://{url}'
            report_url = f'{url}/#/QAPlatform/HttpAutoTestService/report/{report_type}/{version}'

            # 是否发送报告(邮件)
            send_email_report = value.get('SEND_EMAIL_REPORT')
            if send_email_report:
                # 收件人
                to = value.get('TO')
                # 抄送人
                cc = value.get('CC')
                if not to:
                    logger.warning('收件人为空，邮件发送测试报告失败')
                to = to.split(',')
                cc = cc.split(',') if cc else None
                try:
                    mail_body = f'执行人：{executor_real_name}\n执行时间：{execute_time}\n执行结果：{testreport_status[result_status]}\n测试报告访问链接：{report_url}'
                    send_mail(subject=mail_subject, body=mail_body, to=to, cc=cc)
                except Exception as e:
                    logger.error(f'邮件发送测试报告失败，原因：{e}')
                    raise e
                else:
                    logger.info('邮件发送测试报告成功')

            # 是否发送报告(钉钉)
            send_dingtalk_report = value.get('SEND_DINGTALK_REPORT')
            if send_dingtalk_report:
                dingtalk_parameter = Parameter.objects.filter(key='DINGTALK', is_deleted=False).first()
                if dingtalk_parameter:
                    value = json.loads(dingtalk_parameter.value)
                    if value:
                        webhook = value.get('WEBHOOK')
                        secret = value.get('SECRET') or None
                        if webhook:
                            try:
                                dingtalk = DingTalkClient(webhook=webhook, secret=secret)
                                dingtalk_text = f'执行人：{executor_real_name}\n执行时间：{execute_time}\n测试报告访问链接：{report_url}'
                                pic_url = f'{url}/{result_status}.png'
                                dingtalk.send_link(title=dingtalk_title, text=dingtalk_text, message_url=report_url,
                                                   pic_url=pic_url)
                            except Exception as e:
                                logger.error(f'钉钉发送测试报告失败，原因：{e}')
                                raise e
                            else:
                                logger.info('钉钉发送测试报告成功')
                        else:
                            logger.warning('webhook为空，钉钉发送测试报告失败')
